package com.itheima.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.constant.MessageConstant;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

/**
 * @author nglsk
 * @version v1.0
 * @date 2019/11/23 20:25
 * @description TODO
 **/
public class QiNiuUtil {
    static Configuration cfg = new Configuration(Region.huadong());

    static String accessKey = "ZcSeUPNpXuMzQKT5IOkrp-zW7g9t85APc2hsIkp_";
    static String secretKey = "vUWqWS2uif2cTjSLRs7tA8JEddmRNa4tXfzeL6Su";
    static String bucket = "health-nglsk";

    /**
     * 文件上传
     *
     * @param img
     * @param fileName
     */
    public static String upload(byte[] img, String fileName) {

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(img, fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

        } catch (QiniuException ex) {
           /* Response r = ex.response;
            JSONObject jsonObject = JSON.parseObject(r.toString());
            return jsonObject.getString("error");*/
           return MessageConstant.PIC_UPLOAD_FAIL;
        }
        return MessageConstant.PIC_UPLOAD_SUCCESS;
    }


    /**
     * 删除文件
     *
     * @param fileName
     */
    public static void delete(String fileName) {

        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(bucket, fileName);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
        }
    }
}

